const favour = require('@koa/router')()
const DB = require('../controllers/db')
const tk = require('../utils/token')

favour.post('/', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      const msg = await DB.userFavorites(ctx.request.body.userName)
      ctx.body = msg
    }
  }
})

favour.post('/delete', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      const msg = await DB.deleteUserFavour(ctx.request.body.videoId, ctx.request.body.userId)
      ctx.body = msg
    }
  }
})

favour.post('/add', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      if (ctx.request.body.videoId && ctx.request.body.userId) {
        const msg = await DB.addUserFavour(ctx.request.body.videoId, ctx.request.body.userId)
        ctx.body = msg
      } else {
        ctx.body = {
          code: 408,
          msg: `未携带必要参数`
        }
      }
    }
  }
})


module.exports = favour